package com.tanhua.dubbo.server.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: RedisCacheInterceptor
 * @Author:王晨晗
 * @Description: 自定义的缓存拦截器
 * @Date: 2021/12/29/11:47
 */
@Component
public class RedisCacheInterceptor implements HandlerInterceptor {
    @Value("${tanhua.cache.enable}")
    private Boolean enable;     //用于是否开启缓存
    @Autowired
    private RedisTemplate<String , String> redisTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否开启缓存
        if (!enable){
            return true;
        }

        //判断请求是否在请求路径中(即controller是否有该请求)
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //判断是否是get请求
        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)){
            return true;
        }

        //判断是否添加了自定义注解
        if (!((HandlerMethod)handler).hasMethodAnnotation(Cache.class)){
            return true;
        }

        //进行缓存命中
        String redisKey = createRedisKey(request);
        String cacheData = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(cacheData)){
            //缓存未命中
            return true;
        }

        //将缓存数据进行响应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(cacheData);

        return false;
    }

    //生成redis的key
    public static String createRedisKey(HttpServletRequest request) throws Exception {
        String url = request.getRequestURI();
        String param = MAPPER.writeValueAsString(request.getParameterMap());
        String token = request.getHeader("Authorization");
        String data = url + "_" + param + "_" + token;

        return "SERVER_CACHE_DATA_" + DigestUtils.md5Hex(data);
    }
}
